package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Config;
import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DefaultHandler implements Handler {
    @Override
    public void handle(Parameter request, OutputStream response) {
        // TODO: [222024321072057/王文薏]
        // 1. 获取请求路径（可能需要将 / 映射到 index.html）
        // 2. 根据 Config.getWebRoot() 构建完整文件路径
        Path filePath = Paths.get(Config.getInstance().getWebRoot(), request.getUrl().equals("/") ? "index.html" : request.getUrl().substring(1));

        try {
            if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
                byte[] fileBytes = Files.readAllBytes(filePath);

                // TODO: [222024321072057/王文薏] 确定并设置正确的 Content-Type (例如 text/html, image/jpeg 等)
                String contentType = Files.probeContentType(filePath);
                // 补充常见类型的探测不足
                if (contentType == null) {
                    String fileNameStr = filePath.getFileName().toString();
                    if (fileNameStr.endsWith(".html") || fileNameStr.endsWith(".htm")) {
                        contentType = "text/html; charset=UTF-8";
                    } else if (fileNameStr.endsWith(".css")) {
                        contentType = "text/css";
                    } else if (fileNameStr.endsWith(".js")) {
                        contentType = "application/javascript";
                    } else if (fileNameStr.endsWith(".png")) {
                        contentType = "image/png";
                    } else if (fileNameStr.endsWith(".jpg") || fileNameStr.endsWith(".jpeg")) {
                        contentType = "image/jpeg";
                    } else {
                        contentType = "application/octet-stream"; // 默认二进制流
                    }

                    // 写入 200 OK 响应头
                    response.write(("HTTP/1.1 200 OK\r\n").getBytes());
                    response.write(("Content-Type: " + contentType + "\r\n").getBytes());
                    response.write(("Content-Length: " + fileBytes.length + "\r\n").getBytes());
                    response.write(("\r\n").getBytes());// 空行分隔头和体

                    // 写入文件内容
                    response.write(fileBytes);
                } else {
                    // 文件不存在或路径错误，返回 404
                    String content = "<h1>404 Not Found</h1><p>The requested resource " + request.getUrl() + " was not found.</p>";
                    response.write(("HTTP/1.1 404 Not Found\r\n").getBytes());
                    response.write(("Content-Type: text/html; charset=UTF-8\r\n").getBytes());
                    response.write(("Content-Length: " + content.getBytes().length + "\r\n").getBytes());
                    response.write(("\r\n").getBytes());
                    response.write(content.getBytes());
                }
            }
        } catch (IOException e) {
            // TODO: [222024321072057/王文薏] 文件读取异常，返回 500 Internal Server Error
                // 文件读取异常，返回500
            try {
                String errorMsg = "<h1>500 Internal Server Error</h1><p>An error occurred while processing the request.</p>";
                byte[] errorBytes = errorMsg.getBytes("UTF-8");
                response.write(("HTTP/1.1 500 Internal Server Error\r\n").getBytes());
                response.write(("Content-Type: text/html; charset=UTF-8\r\n").getBytes());
                response.write(("Content-Length: " + errorBytes.length + "\r\n").getBytes());
                response.write(("\r\n").getBytes());
                response.write(errorBytes);
                // 记录异常日志（实际应用中建议使用日志框架）
                e.printStackTrace();
            } catch (IOException ex) {
                // 响应写入失败时的异常处理
                ex.printStackTrace();
            }
        } finally {
                try {
                    response.flush();
                } catch (IOException e) { /* ignore */ }
            }
    }
}

